//
//  MyTableView.m
//  1gene
//
//  Created by 1jiyin on 16/2/26.
//  Copyright © 2016年 1jiyin. All rights reserved.
//
//*******************我的*******************
#import "MyTableView.h"


@interface MyTableView()
@property(nonatomic,assign)CGFloat myScore;

@property(nonatomic,copy)UserModel *userModel;
@end
@implementation MyTableView
-(instancetype)initWithFrame:(CGRect)frame style:(UITableViewStyle)style WithData:(NSArray *)array andImgData:(NSArray *)imgData
{
    if (self = [super initWithFrame:frame style:style]) {
        _myScore=5000;
        self.showsVerticalScrollIndicator=NO;
        _dataArray=[NSMutableArray arrayWithArray:array];
        _imgDataArray=[NSMutableArray arrayWithArray:imgData];
        self.delegate=self;
        self.dataSource=self;
        self.showsHorizontalScrollIndicator=NO;
        self.showsVerticalScrollIndicator=NO;
        self.tableHeaderView=[self createTableHeaderView];
        self.tableFooterView=[UIView new];
        self.separatorStyle=UITableViewCellSeparatorStyleNone;
        [self getUserInfo];
        
        self.header=[MJRefreshNormalHeader headerWithRefreshingBlock:^{
             [self getUserInfo];
        }];
    }
    return self;
}
-(UIView *)createTableHeaderView
{
    UIView *view=[[UIView alloc]initWithFrame:CGRectMake(0, 0, self.frame.size.width, 170)];
    view.backgroundColor=[UIColor whiteColor];
    
    UIImageView *backgroundImgView=[[UIImageView alloc]initWithFrame:view.bounds];
    backgroundImgView.image=[UIImage imageNamed:@"myBackgroundImage.png"];
    [view addSubview:backgroundImgView];
    //view.backgroundColor=[UIColor colorWithPatternImage:[UIImage imageNamed:[[NSBundle mainBundle]pathForResource:@"myBackgroundImage.png" ofType:nil]]];
    //我的
    UILabel *myLab=[[UILabel alloc]initWithFrame:CGRectMake(0, 0, self.frame.size.width, 73)];
    myLab.text=@"我的";
    myLab.textAlignment=NSTextAlignmentCenter;
    myLab.font=[UIFont systemFontOfSize:25];
    myLab.textColor=[UIColor colorWithRed:250/255.0 green:254/255.0 blue:254/255.0 alpha:1];
    [view addSubview:myLab];
    
    //头像
    UIImageView *headImgView=[[UIImageView alloc]initWithFrame:CGRectMake(20, CGRectGetMaxY(myLab.frame)+(60-self.frame.size.width*(60/375.0))/2.0, self.frame.size.width*(60/375.0), self.frame.size.width*(60/375.0))];
    headImgView.image = [UIImage imageNamed:@"155x155-1"];
    [headImgView sd_setImageWithURL:[NSURL URLWithString:_userModel.user_profile[@"avatar_url"]] placeholderImage:[UIImage imageNamed:@"155x155-1.png"]];
    headImgView.backgroundColor = [UIColor lightGrayColor];
    NSLog(@"得到的用户头像========%@",_userModel.user_profile[@"avatar_url"]);
    headImgView.layer.cornerRadius=self.frame.size.width*(60/375.0)/2.0;
    headImgView.layer.masksToBounds=YES;
    _headImgView=headImgView;
    [view addSubview:headImgView];
    
    NSData *data=[NSData dataWithContentsOfURL:[NSURL URLWithString:_userModel.user_profile[@"avatar_url"]]];
    UIImage *myHeadImage=[UIImage imageWithData:data];
    headImgView.image=myHeadImage;
    
    
    
    
    
    
    
    
    
    
    //盖按钮
    UIButton *userHeadBtn=[UIButton buttonWithType:UIButtonTypeCustom];
    userHeadBtn.frame=headImgView.frame;
    [userHeadBtn addTarget:self action:@selector(userHeadImageViewBtnClick:) forControlEvents:UIControlEventTouchUpInside];
    [view addSubview:userHeadBtn];
    
    
    //会员
    UIImageView *memberImageView=[[UIImageView alloc]initWithFrame:CGRectMake(headImgView.frame.origin.x+(headImgView.frame.size.width-20)/2.0, CGRectGetMaxY(headImgView.frame)+3, 20, 20)];
    memberImageView.image=[UIImage imageNamed:[NSString stringWithFormat:@"member_%@",_userModel.user_profile[@"vip"]]];
    [view addSubview:memberImageView];
    
    
    
    
    
    
    
    //昵称
    UILabel *nameLab=[[UILabel alloc]initWithFrame:CGRectMake(CGRectGetMaxX(headImgView.frame)+10, CGRectGetMaxY(myLab.frame), self.frame.size.width*(100/375.0), 30)];
    nameLab.text=[NSString stringWithFormat:@"昵称:%@",_userModel.user_profile[@"nikename"]];
    nameLab.textColor=[UIColor whiteColor];
    nameLab.font=[UIFont systemFontOfSize:14];
    if ([self calculateWidthWithLable:nameLab]<=self.frame.size.width*(100/375.0)) {
        nameLab.frame=CGRectMake(nameLab.frame.origin.x, nameLab.frame.origin.y, [self calculateWidthWithLable:nameLab], nameLab.frame.size.height);
    }
    [view addSubview:nameLab];
    
    //积分
    
    UILabel *scoreLab=[[UILabel alloc]initWithFrame:CGRectMake(CGRectGetMaxX(nameLab.frame)+5, nameLab.frame.origin.y+7, self.frame.size.width*(65/375.0), 16)];
    if ([_userModel.user_profile[@"credits"] isKindOfClass:[NSNull class]]) {
        _myScore=0;
    }else{
        _myScore=[_userModel.user_profile[@"credits"] floatValue];
    }
    [self.myDelegate returnScore:_myScore];
    scoreLab.text=[NSString stringWithFormat:@"积分:%.1f",_myScore];
    scoreLab.textAlignment=NSTextAlignmentCenter;
    scoreLab.layer.borderColor=[UIColor colorWithRed:215/255.0 green:123/255.0 blue:32/255.0 alpha:1].CGColor;
    scoreLab.layer.borderWidth=1.0;
    scoreLab.layer.cornerRadius=5.0;
    
    
    scoreLab.textColor=[UIColor colorWithRed:156/255.0 green:105/255.0 blue:57/255.0 alpha:1];
    scoreLab.font=[UIFont systemFontOfSize:10];
    [view addSubview:scoreLab];
    //
    UIButton *scoreBtn=[UIButton buttonWithType:UIButtonTypeCustom];
    scoreBtn.frame=scoreLab.frame;
    [scoreBtn addTarget:self action:@selector(scoreBtnClick:) forControlEvents:UIControlEventTouchUpInside];
    [view addSubview:scoreBtn];
    _scoreLab=scoreLab;
    _scoreBtn=scoreBtn;
    
    
    //签到
    UIImageView *signInImgView=[[UIImageView alloc]initWithFrame:CGRectMake(CGRectGetMaxX(scoreLab.frame)+15, scoreLab.frame.origin.y-5, 25, 25)];
    signInImgView.image=[UIImage imageNamed:@"44X44-1.png"];
    [view addSubview:signInImgView];
    
    
    UILabel *signLab=[[UILabel alloc]initWithFrame:CGRectMake(CGRectGetMaxX(signInImgView.frame)+3, scoreLab.frame.origin.y-5, self.frame.size.width-CGRectGetMaxX(signInImgView.frame)-10, 30)];
    signLab.text=@"签到";
    //signLab.textAlignment=NSTextAlignmentCenter;
    signLab.textColor=[UIColor whiteColor];
    signLab.font=[UIFont systemFontOfSize:14];
    [view addSubview:signLab];
    
    //个性签名
    UILabel *specialNameLab=[[UILabel alloc]initWithFrame:CGRectMake(nameLab.frame.origin.x, CGRectGetMaxY(nameLab.frame), nameLab.frame.size.width+scoreLab.frame.size.width, 30)];
    specialNameLab.text=[NSString stringWithFormat:@"个性签名:%@",_userModel.user_profile[@"signatures"]];
    specialNameLab.font=[UIFont systemFontOfSize:14];
    specialNameLab.textColor=[UIColor whiteColor];
    [view addSubview:specialNameLab];
    
    //抽奖
    UIImageView *lotteryImgView=[[UIImageView alloc]initWithFrame:CGRectMake(CGRectGetMaxX(scoreLab.frame)+15, specialNameLab.frame.origin.y+2, 25, 25)];
    lotteryImgView.image=[UIImage imageNamed:@"44X44-2.png"];
    [view addSubview:lotteryImgView];
    
    
    UILabel *lotteryLab=[[UILabel alloc]initWithFrame:CGRectMake(CGRectGetMaxX(signInImgView.frame)+3, specialNameLab.frame.origin.y, self.frame.size.width-CGRectGetMaxX(signInImgView.frame)-20, 30)];
    lotteryLab.text=@"抽奖";
    //signLab.textAlignment=NSTextAlignmentCenter;
    lotteryLab.textColor=[UIColor whiteColor];
    lotteryLab.font=[UIFont systemFontOfSize:14];
    [view addSubview:lotteryLab];
    //盖按钮
    UIButton *signInBtn=[UIButton buttonWithType:UIButtonTypeCustom];
    signInBtn.frame=CGRectMake(signInImgView.frame.origin.x, signInImgView.frame.origin.y, signInImgView.frame.size.width+3+signLab.frame.size.width, signLab.frame.size.height);
    [signInBtn addTarget:self action:@selector(signInBtnClick:) forControlEvents:UIControlEventTouchUpInside];
    [view addSubview:signInBtn];
    
    UIButton *lotteryBtn=[UIButton buttonWithType:UIButtonTypeCustom];
    lotteryBtn.frame=CGRectMake(lotteryImgView.frame.origin.x, lotteryImgView.frame.origin.y, lotteryImgView.frame.size.width+3+lotteryLab.frame.size.width, lotteryLab.frame.size.height);
    [lotteryBtn addTarget:self action:@selector(lotteryBtnClick:) forControlEvents:UIControlEventTouchUpInside];
    [view addSubview:lotteryBtn];

    
    
    return view;
}

#pragma mark 积分
-(void)scoreBtnClick:(UIButton *)sender
{
    [self.myDelegate gotoMyScoreViewController:_myScore];
}
#pragma mark 点击用户头像
-(void)userHeadImageViewBtnClick:(UIButton *)sender
{
    NSLog(@"++++++++");
    [self.myDelegate userHeadImageViewClick];
}


#pragma mark 签到
-(void)signInBtnClick:(id)sender
{
    NSLog(@"签到");
    [self.myDelegate signIn];
}
#pragma mark 抽奖
-(void)lotteryBtnClick:(id)sender
{
    NSLog(@"抽奖");
    [self.myDelegate choujiang];
}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return _dataArray.count;
}
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    UITableViewCell *cell=[tableView dequeueReusableCellWithIdentifier:@"cell"];
    if (cell==nil) {
        cell=[[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"cell"];
    }
    for (id subView in cell.contentView.subviews) {
        [subView removeFromSuperview];
    }
    cell.selectionStyle=UITableViewCellSelectionStyleNone;
    cell.backgroundColor=[UIColor whiteColor];
    //标识图
    UIImageView *identificationImgView=[[UIImageView alloc]initWithFrame:CGRectMake(30, ((self.frame.size.height-150-20)/6.0-(((self.frame.size.height-150-20)/6.0)/2.0+10))/2.0, ((self.frame.size.height-150-20)/6.0)/2.0+10, ((self.frame.size.height-150-20)/6.0)/2.0+10)];
    identificationImgView.image=[UIImage imageNamed:_imgDataArray[indexPath.row]];
    identificationImgView.layer.cornerRadius=(((self.frame.size.height-150-20)/6.0)/2.0)/2.0;
    identificationImgView.layer.masksToBounds=YES;
    [cell.contentView addSubview:identificationImgView];
    
    //标题
    UILabel *lab=[[UILabel alloc]initWithFrame:CGRectMake(self.frame.size.width*(240/750.0), 0, self.frame.size.width*(190/750.0)+20, (self.frame.size.height-150)/6.0)];
    lab.text=_dataArray[indexPath.row];
    lab.textColor=[UIColor blackColor];
    lab.font=[UIFont systemFontOfSize:16];
    [cell.contentView addSubview:lab];
    
    //向右的小三角
    UIImageView *imgView=[[UIImageView alloc]initWithFrame:CGRectMake(self.frame.size.width-60, ((self.frame.size.height-150-20)/6.0)/3.0, ((self.frame.size.height-150-20)/6.0)/3.0, ((self.frame.size.height-150-20)/6.0)/3.0)];
    imgView.image=[UIImage imageNamed:@"app_right"];
    [cell.contentView addSubview:imgView];
    
    
    //下划线
    UIView *line=[[UIView alloc]initWithFrame:CGRectMake(0, ((self.frame.size.height-150-20)/6.0)-0.5, self.frame.size.width, 0.5)];
    line.backgroundColor=[UIColor grayColor];
    [cell.contentView addSubview:line];
    return cell;
}
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    NSLog(@"*************%ld",indexPath.row);
    [self.myDelegate clickCell:indexPath.row];
}
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return (self.frame.size.height-150-20)/6.0;
}


//根据文字计算宽度和高度
-(CGFloat)calculateWidthWithLable:(UILabel *)label
{
    CGSize size=[label.text sizeWithAttributes:[NSDictionary dictionaryWithObjectsAndKeys:label.font,NSFontAttributeName, nil]];
    return size.width;
}
//获取用户信息
-(void)getUserInfo
{
    AFHTTPRequestOperationManager * manager=[AFHTTPRequestOperationManager manager];
    manager.requestSerializer=[AFHTTPRequestSerializer serializer];
    manager.responseSerializer=[AFHTTPResponseSerializer serializer];
    
    NSUserDefaults *user=[NSUserDefaults standardUserDefaults];
    NSString *token= [user objectForKey:@"token"];
    
    [manager GET:[NSString stringWithFormat:@"%@%@",UserInfo,token] parameters:nil success:^(AFHTTPRequestOperation *operation, id responseObject) {
        [self.header endRefreshing];
        NSDictionary * dic = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableContainers error:nil];
        NSLog(@"userInfo===%@",dic);
        if (dic) {
            _userModel=[[UserModel alloc]initWithDictionary:dic];
            self.getUserInfoData(dic);
            
            NSUserDefaults *myUser=[NSUserDefaults standardUserDefaults];
            [myUser setObject:_userModel.got_credit forKey:@"got_credit"];
            [myUser synchronize];
            dispatch_async(dispatch_get_main_queue(), ^{
                self.tableHeaderView=[self createTableHeaderView];
                NSLog(@"=========");
            });
        }
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        [self.header endRefreshing];
        NSLog(@"%@",error.localizedDescription);
    }];
    
}

#pragma mark === 暂时不用清除缓存=====
-(void)myClearCacheAction{
    dispatch_async(
                   dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0)
                   , ^{
                       NSString *cachPath = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) objectAtIndex:0];
                       
                       NSArray *files = [[NSFileManager defaultManager] subpathsAtPath:cachPath];
                       NSLog(@"files :%lu",(unsigned long)[files count]);
                       for (NSString *p in files) {
                           NSError *error;
                           NSString *path = [cachPath stringByAppendingPathComponent:p];
                           if ([[NSFileManager defaultManager] fileExistsAtPath:path]) {
                               NSLog(@"开始清理缓存");
                               [[NSFileManager defaultManager] removeItemAtPath:path error:&error];
                           }
                       }
                       [self performSelectorOnMainThread:@selector(clearCacheSuccess) withObject:nil waitUntilDone:YES];});
}
-(void)clearCacheSuccess
{
    NSLog(@"清理成功");
    
}
/*
// Only override drawRect: if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
- (void)drawRect:(CGRect)rect {
    // Drawing code
}
*/

@end







































